<?php
/**
 * @copyright meila.com
 * @author wangtao5@
 * @name 发布接口
 * @param
 *         $nick = 作用
 *
 *
 */
include('../../__global.php');
include(SERVER_ROOT_PATH.'/include/config/dataRule/ml_datarule_content.php');
include(SERVER_ROOT_PATH.'/include/config/ml_queue_name.php');
class aj_publish extends ml_controller
{
    private $content;
    private $pic_id;
    private $gd_title;
    private $gd_price;
    private $gd_url;
    private $gd_pic;
    private $type_xrank;
    private $pb2weibo;
    private $gd_complete=0;//宝贝完整判断表示
    private $arrAlert = array(
        'content' => 'content',
        'content_len' => 'content_len',
        'gd_title_len' => 'gd_title_len',
        'gd_price' => 'gd_price',
        'gd_url' => 'gd_url',
        'gd_pic' => 'gd_pic',
        'gd_exit' => 'gd_exit',
    );

    private $infoAndName;
    private $col_info;
    private $col_id;
    private $uid;

    function initParam()
    {
        /**
         * @todo get post
         */
        $this->content = $this->input('content', 'P', '');
        $this->pic_id =  $this->input('pic_id', 'P', 0);
        $this->gd_title = $this->input('gd_title', 'P', '');
        $this->gd_price = $this->input('gd_price', 'P', 0);
        $this->gd_url = $this->input('gd_url', 'P', '');
        $this->gd_pic = $this->input('gd_pic', 'P', '');
        $this->pb2weibo = $this->input('pb2weibo','P');
        $this->col_id = intval($this->input('col_id','P'));
        $this->ctype = (int)$this->input('ctype','P',1);

        $this->uid = $this->__visitor['uid'];
        $this->content = preg_replace('/\s+/',' ', $this->content);

    }
    /**
     * @develop_template
     * 检查参数合法性
     */
    function checkParam()
    {
        $this->check_referer();
        if(!$this->check_permission(ML_PERMISSION_LOGIN_ONLY)) {
            return $this->api_output(ML_RCODE_NOLOGIN);
        }
        else if(!$this->check_permission(ML_PERMISSION_LOGIN_CANWRITE)) {
            return $this->api_output(ML_RCODE_NOACTIVE);
        }

        /**
         * @todo 待加敏感词过滤
         */
        //$this->content = Tool_keyword::filterSensitiveWord($this->content);

        if(empty($this->content)){
            $this->api_output(ML_RCODE_PARAM , '', $this->arrAlert['content']);
        }

        if(!empty($this->pic_id)){
            if(!ml_tool_picid::ispid($this->pic_id)){
                $this->api_output(ML_RCODE_PARAM , '', $this->arrAlert['gd_pic']);
            }
        }

        if(Tool_string::str_width($this->content) > ML_DATARULE_CONTENT_MAXLEN)
        $this->api_output(ML_RCODE_PARAM , '', $this->arrAlert['content_len']);

        if(!empty($this->gd_title)) $this->gd_complete++;
        if(!empty($this->gd_url)) $this->gd_complete++;
        if(!empty($this->gd_price)) $this->gd_complete++;


        if(0 === $this->gd_complete){
            if(!empty($this->pic_id))
            $this->type_xrank = ML_CONTENT_XRANK_IMG;
        }else if(3 === $this->gd_complete){
            if(Tool_string::str_width($this->gd_title) > ML_DATARULE_CONTENT_TITLE_MAXLEN)
            $this->api_output(ML_RCODE_PARAM , '', $this->arrAlert['gd_title_len']);

            if(!is_numeric($this->gd_price))
            $this->api_output(ML_RCODE_PARAM , '', $this->arrAlert['gd_price']);

            if(!preg_match(ML_DATARULE_BASE_URL , $this->gd_url))
            $this->api_output(ML_RCODE_PARAM ,'', $this->arrAlert['gd_url']);

            if(empty($this->gd_pic) || !preg_match(ML_DATARULE_BASE_URL , $this->gd_pic))
            $this->api_output(ML_RCODE_PARAM ,'', $this->arrAlert['gd_pic']);

            if(empty($this->pic_id)){
                $this->type_xrank = ML_CONTENT_XRANK_GOODS;
                $fetchImg = 'http://'.ML_CNF_DOMAIN.'/image/fetch_pic_to_goods.php';
                $data['uid'] = $this->__visitor['uid'];
                $data['url'] = $this->gd_pic;
                $rs = Tool_http::post($fetchImg, $data);
                
                $rs = json_decode($rs, true);
                if ($rs['code'] == ML_RCODE_SUCC) {
                    $this->pic_id = $rs['data']['pid'];
                } else {

                    $this->api_output(ML_RCODE_PARAM ,'', $this->arrAlert['gd_pic']);
                }

            }else{
                $this->type_xrank = ML_CONTENT_XRANK_IMGOODS;
            }
        }else{
            $this->api_output(ML_RCODE_PARAM ,'', $this->arrAlert['gd_exit']);
        }


    }
    /**
     * @develop_template
     * 核心业务逻辑
     */
    function main()
    {
        $oGenerator = new ml_model_dbIdGenerator();
        $time = time();
        $uid = $this->__visitor['uid'];

        $aNicks = ml_tool_nick::findAllAtNick($this->content);
        if($aNicks)
        {
            $aN2u = ml_tool_nick::nicks2uids($aNicks);
        }

        // 对内容中的链接进行处理
        $this->content = ml_tool_formatContent::repalcelink ( $this->content );

        if(!empty($this->pic_id)){  /* 有图片的处理方式 */
            $content_res = $oGenerator->get_content_rid($uid, $content_rid);
            $userfeed_res = $oGenerator->get_userfeed_rid($uid, $userfeed_rid);
            if(!$content_res && $userfeed_res){
                $this->api_output(ML_RCODE_BUSY , '' , ML_RMESSAGE_BUSY);
            }
            $content_data['type_xrank'] = $this->type_xrank;
            $userfeed_data['content_rid'] = $content_data['rid'] = $content_rid;
            $userfeed_data['uid'] = $content_data['uid'] = $uid;
            $userfeed_data['content'] = $content_data['content'] = $this->content;
            $userfeed_data['pic_id'] = $content_data['pic_id'] = $this->pic_id;
            $userfeed_data['rid'] = $content_data['userfeed_rid'] = $userfeed_rid;
            $userfeed_data['ctime'] = $content_data['ctime'] = date('Y-m-d H:i:s', $time);

            $userfeed_data['type'] = Tool_dataMultiplex::isAttribute(ML_CONTENT_XRANK_GOODS, $this->type_xrank) ? ML_FEED_TYPE_PUB_DOTEY : ML_FEED_TYPE_PUB_PIC;
            $userfeed_data['cip'] = $content_data['cip'] = Tool_ip::get_real_ip();
            if(3 === $this->gd_complete){
                $oTinyurl = new ml_model_mcTinyurl ();
                $tinyurl = $oTinyurl->longurl2tiny ( $this->gd_url );
                $content_data['gd_title'] = $this->gd_title;
                $content_data['gd_price'] = $this->gd_price;
                $content_data['gd_info'] = array(
                    'gd_url'=>$this->gd_url,
                    'gd_tinyurl' => $tinyurl,
                    'gd_pic'=>$this->gd_pic,
                );
                    
                $userfeed_data['feed_info'] = array(
                    'gd_title'=>$this->gd_title,
                    'gd_price'=>$this->gd_price,
                    'gd_url'=>$this->gd_url,
                    'gd_pic'=>$this->gd_pic,
                );

                //将用户输入的昵称保存备查 shaopu@
                if(!empty($aN2u))
                {
                    $content_data['gd_info']['nick2uid']= $aN2u;
                    $userfeed_data['feed_info']['nick2uid']= $aN2u;
                }
            }
            $oContent = new ml_model_dbContent();
            $rDb_content = $oContent->insert_content($content_data);
            if($rDb_content){
                if(!empty($this->gd_title))
                $rMq_analyse = ml_tool_sendMq::goods_title_analyse($content_rid, $this->gd_title);
                $rMq_content = ml_tool_sendMq::goods_add_content($content_data);

                ml_tool_sendMq::search_content('A', $content_rid);

                if(!empty($this->col_id)&&$this->col_id>0){//收集到专辑
                    $modelRe=new ml_model_dbCollectionRe();
                    $modelBox=new ml_model_dbCollectionBox();
                    $comModel=new ml_model_dbCollectionComment();
                    $this->get_col_id($modelBox);//其中的name用来插入评论表，作为冗余name
                    $this->col_info_factory();
                    $modelRe->submitRepost($this->uid,$this->col_id,$content_rid,'');//向关系表中加一个记录
                    $modelBox->submitRepost($this->uid,$this->col_id,$this->col_info);//采集数+1&update专辑的前9个图片
                    $comModel->insert_comment($content_rid, $this->infoAndName['name'], $this->uid, $this->col_id, '');
                    $redis=new ml_model_rdsCount();
                    $redis->incrColCnt($content_rid);//宝贝被转采数+1
                }
                    
            }
        }else{
            $userfeed_res = $oGenerator->get_userfeed_rid($uid, $userfeed_rid);
            if(!$userfeed_res){
                $this->api_output(ML_RCODE_BUSY , '' , ML_RMESSAGE_BUSY);
            }
            $userfeed_data['rid'] = $userfeed_rid;
            $userfeed_data['uid'] = $uid;
            $userfeed_data['content'] = $this->content;
            $userfeed_data['ctime'] = date('Y-m-d H:i:s', $time);
            $userfeed_data['type'] = ML_FEED_TYPE_PUB_SHORT;
            //将用户输入的昵称保存备查 shaopu@
            if(!empty($aN2u))
            {
                $userfeed_data['feed_info']['nick2uid'] = $aN2u;
            }
        }

        $rid = $content_rid ? $content_rid : $userfeed_rid;

        if(!empty($aN2u))
        ml_tool_sendMq::atme_in_content($uid , $rid , array_values($aN2u));


        $oUserfeed = new ml_model_dbUserfeed();
        $rDb_userfeed = $oUserfeed->insert_content($userfeed_data);



        /**
         * 增加内容数统计
         */
        $oRedis = new ml_model_rdsCount();
        $oRedis->incrUserContentcnt($uid);
        $oRedis->incrUserfeedcnt($uid);

        /**
         * @todo 发布到微博待处理
         */
        if($this->pb2weibo =='true' ){
            
            $o3rd = new ml_model_db3rdService();
            $rs = $o3rd -> get3rdServiceUser($this->uid,1 ,$serData);
            if($rs){
                $wb['access_token']=$serData['access_token'];
            }else{
                $session=$this->getSession();
                $wb['access_token']=$session->getVal ( 'access_token' );
            }
            $wbcontent=urldecode($this->content);
            $wbgd_title=urldecode($this->gd_title);
            if($wbcontent=='分享宝贝'){
                $wbcontent='我刚刚在 @美啦 分享了【'.$wbgd_title.'】 >> http://meila.com'. ml_tool_urlMaker::show_goods($rid);
            }elseif($wbcontent=='分享图片'){
                $wbcontent='我刚刚在 @美啦 发布了我的搭配照片 >> http://meila.com'.ml_tool_urlMaker::show_goods($rid);
            }else{
                if(empty($content_rid)){
                    $wbcontent=$wbcontent.' >> http://meila.com'.ml_tool_urlMaker::person_feed($uid);
                }else{
                    $wbgd_title=empty($wbgd_title)?'':'【'.$wbgd_title.'】';
                    $wbcontent=$wbcontent.' '.$wbgd_title.' >> http://meila.com'.ml_tool_urlMaker::show_goods($rid);
                }
            }
            switch($this->type_xrank){
                case ML_CONTENT_XRANK_GOODS:
                    $wb['picurl']=$this->gd_pic;
                    break;
                case ML_CONTENT_XRANK_IMG:
                case ML_CONTENT_XRANK_IMGOODS:
                    $wb['picurl']=ml_tool_picid::pid2url($this->pic_id,ML_USER_PICSIZE_SHOW,ML_PICTYPE_CONTENT);
                    break;
                default:
                    break;
            }
            $wb['content']=$wbcontent;
            $service_id = 1; //weibo
            ml_tool_sendMq::send_3rdweibo($service_id,$wb);
        }

        if(!$rDb_userfeed){
            $this->api_output(ML_RCODE_BUSY);
        }else{
            $content_data['nick'] = $this->__visitor['nickname'];
            $content_data['ctime'] = date('Y-m-d H:i:s');
                
            $data = array('feed_rid' => $userfeed_rid, 'uid' => $uid);
            ml_tool_sendMq::add_feed($data);
            ml_tool_sendMq::add_likeandfan($uid, $rid);
            if(!empty($this->pic_id) && $this->ctype){
                $outData['ctype'] = $this->ctype;
                $pin_biz =new  ml_biz_pin_content();
                $outData['data'] = $pin_biz->output($this->__visitor['uid'],array($content_data),true);
                $outData['data'] = str_replace("height:0px","",$outData['data'][0]);
            }else{
                $outData['ctype'] = $this->ctype;
                $htmlModel=new ml_biz_feed_user();
                $outData['data']=$htmlModel->output(array($userfeed_data), $this->__visitor['uid']);
                $outData['data'] = $outData['data'][0];
            }
                
            $at_num = count($aN2u);
            switch($this->type_xrank){
                case ML_CONTENT_XRANK_GOODS:
                    ml_tool_actionlog::publish_gd($uid , $rid, $this->gd_url, $this->content , false ,$this->gd_price, $at_num);
                    break;
                case ML_CONTENT_XRANK_IMG:
                    ml_tool_actionlog::publish_pic($uid , $rid, $this->content , $at_num);
                    break;
                case ML_CONTENT_XRANK_IMGOODS:
                    ml_tool_actionlog::publish_gd($uid , $rid, $this->gd_url, $this->content,true ,$this->gd_price, $at_num);
                    break;
                default:
                    ml_tool_actionlog::publish_txt($uid , $rid, $this->content , $at_num);
            }
            $this->api_output(ML_RCODE_SUCC, $outData);
        }
    }
    private function get_col_id(&$model){
        $this->infoAndName=$model->getColinfo($this->uid, $this->col_id);
        if (empty($this->infoAndName['name'])) {
            $this->api_output(ML_RCODE_PARAM,'','wrong col_id');
        }

    }
    private function col_info_factory(){
        $this->col_info=$this->infoAndName['col_info'];
        $this->col_info=empty($this->col_info)?array():$this->col_info;
        if(count($this->col_info)>=9) array_pop($this->col_info);
        $this->col_info=array_merge(array($this->pic_id),$this->col_info);

    }
}

new aj_publish();
